package com.efounder.chat.activity;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.http.EFHttpRequest.HttpRequestListener;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

//import com.nostra13.universalimageloader.core.DisplayImageOptions;

public class AddFriendUserDetailActivity extends BaseActivity {
    private TextView userNameView;
    private TextView phoneView;
    private TextView bianHaoView;
    private TextView aDNameView;
    private ImageView avatarImagView;
    private String userId;
    private Button addToFriendButton;
    private User addUser;
    private ProgressDialog progressDialog;
    private MyHandler myHandler;
    private User addFriendUser;
    //private ImageLoader imageLoader;
//    private DisplayImageOptions options;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_contact);
        //initImageLoader();
        myHandler = new MyHandler();
        initView();

        if (getIntent().hasExtra("user")) {
            addFriendUser = (User) getIntent().getSerializableExtra(
                    "user");
            userId = String.valueOf(addFriendUser.getId());
            dialog = new ProgressDialog(this);
            dialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.show();
            getAddUserInfo(Integer.valueOf(userId), AddFriendUserDetailActivity.this, new AddFriendCallBack() {


                @Override
                public void addFriendCallBack(User user) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    initData(user);
                }
            });
        } else if (getIntent().hasExtra("userID")) {
            userId = getIntent().getStringExtra("userID");
            dialog = new ProgressDialog(this);
            dialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.show();
            getAddUserInfo(Integer.valueOf(userId), AddFriendUserDetailActivity.this, new AddFriendCallBack() {


                @Override
                public void addFriendCallBack(User user) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    initData(user);
                }
            });
        } else if (getIntent().hasExtra("organizationUser")) {
            //从组织机构跳转过来的
            User organizationUser = (User) getIntent().getSerializableExtra(
                    "organizationUser");
            userId = String.valueOf(organizationUser.getId());
            if (userId.equals("-1")) {
                userId = "";
            }
            initData(organizationUser);

        }

    }

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.wrchatview_details));
        userNameView = (TextView) findViewById(R.id.iconname);
        phoneView = (TextView) findViewById(R.id.tv_phone);
        bianHaoView = (TextView) findViewById(R.id.tv_no);
        aDNameView = (TextView) findViewById(R.id.tv_areauser);
        addToFriendButton = (Button) findViewById(R.id.focus);
        avatarImagView = (ImageView) findViewById(R.id.icon);
    }

    private void initData(final User user) {
        if (addFriendUser != null) {
            userNameView.setText(addFriendUser.getNickName());
            phoneView.setText(addFriendUser.getMobilePhone());
            bianHaoView.setText(String.valueOf(addFriendUser.getId()));
            // aDNameView.setText(addFriendUser.getAdName());
            //imageLoader.displayImage(URLModifyDynamic.getInstance().replace(user.getAvatar()), avatarImagView, options);
            LXGlideImageLoader.getInstance().showUserAvatar(this,avatarImagView,user.getAvatar());
        } else {
            userNameView.setText(user.getNickName());
            phoneView.setText(user.getMobilePhone());
            bianHaoView.setText(userId);
            aDNameView.setText("");
            if (getIntent().hasExtra("organizationUser")) {
                aDNameView.setText(user.getEmail());
            }
//            imageLoader.displayImage(URLModifyDynamic.getInstance().replace(user.getAvatar()), avatarImagView, options);
            LXGlideImageLoader.getInstance().showUserAvatar(this,avatarImagView,user.getAvatar());

        }

        addToFriendButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 从数据库得到所有的联系人
                List<User> friends = WeChatDBManager.getInstance().getallFriends();

                List<Integer> ids = new ArrayList<Integer>();// 数据库中存在的用户id
                if (friends != null) {
                    for (User user : friends) {
                        ids.add(user.getId());

                    }
                }

                if (userId.equals("")) {
                    ToastUtil.showToast(AddFriendUserDetailActivity.this, ResStringUtil.getString(R.string.wrchatview_not_obtained));
                    return;
                }
                if (ids.contains(Integer.valueOf(userId))) {
                    ToastUtil.showToast(AddFriendUserDetailActivity.this,
                            ResStringUtil.getString(R.string.wrchatview_already_you_friend));
                } else if (EnvironmentVariable.getProperty(CHAT_USER_ID).equals(userId)) {
                    ToastUtil.showToast(AddFriendUserDetailActivity.this,
                            ResStringUtil.getString(R.string.wrchatview_not_add_youself));
                } else {
                    addUser = new User();
                    addUser.setId(user.getId());
                    addUser.setNickName(user.getNickName());

                    searchUser(userId);
                }

            }
        });
    }

    private void searchUser(String uid) {
        progressDialog = new ProgressDialog(AddFriendUserDetailActivity.this);

        progressDialog.setMessage(ResStringUtil.getString(R.string.wrchatview_sending_friend));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        final String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        try {
            password = URLEncoder.encode(password, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        String url = GetHttpUtil.ROOTURL
                + "/IMServer/user/applyAddFriend?userId=" + userid
                + "&passWord=" + password + "&friendUserId=" + uid;
        httpRequest.httpGet(url);
        httpRequest.setHttpRequestListener(new HttpRequestListener() {

            @Override
            public void onRequestSuccess(int requestCode, String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String info = jsonObject.getString("result");
                    if ("success".equals(info)) {
                        GetHttpUtil.getUserInfo(Integer.valueOf(userId), AddFriendUserDetailActivity.this,
                                new GetHttpUtil.GetUserListener() {
                                    @Override
                                    public void onGetUserSuccess(User user) {
                                        addUser = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(userId));
                                        addUser.setState(User.SENT);//好友申请已发送
                                        addUser.setIsRead(true);
                                        addUser.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                                        addUser.setTime((System.currentTimeMillis()));
                                        WeChatDBManager.getInstance().insertSendNewFriendApply(addUser);
                                        //myHandler.sendEmptyMessage(1);
                                    }

                                    @Override
                                    public void onGetUserFail() {

                                    }
                                });
                        myHandler.sendEmptyMessage(1);
                    }
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onRequestFail(int requestCode, String message) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                ToastUtil.showToast(AddFriendUserDetailActivity.this, ResStringUtil.getString(R.string.wrchatview_send_fail));

            }
        });
        // WeChatHttpRequest.

    }

    @Override
    public void back(View view) {
        finish();
    }

    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
//						//延时1.5秒
//						new Handler().postDelayed(new Runnable() {
//							public void run() {
//							}
//
//						}, 1500);
                    }
                    new AlertDialog.Builder(AddFriendUserDetailActivity.this).
                            setMessage(ResStringUtil.getString(R.string.wrchatview_sended_friend)).setTitle(ResStringUtil.getString(R.string.wrchatview_prompt)).
                            setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            }).show();
                    break;

            }
        }
    }

    /**
     * 异步加载头像
     */
//    public void initImageLoader() {
//        // 初始化异步加载图片的类
//        imageLoader = ImageLoader.getInstance();
//        // 设置异步加载图片的配置信息
//        options = ImageUtil.getImageLoaderOptions(R.drawable.default_useravatar);
//    }

    /**
     * 得到用户信息
     *
     * @param uid 用户id
     */
    public void getAddUserInfo(int uid, final Context context, final AddFriendCallBack addFriendCallBack) {

        EFHttpRequest httpRequest = new EFHttpRequest(TAG);
        String url = GetHttpUtil.ROOTURL
                + "/IMServer/user/getOtherUserByUserId?otherUserId=" + uid;
        httpRequest.httpGet(url);
        httpRequest.setHttpRequestListener(new HttpRequestListener() {

            @Override
            public void onRequestSuccess(int requestCode, String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response)
                            .getJSONObject("user");

                    int id = jsonObject.getInt("userId");
                    User user = new User();
                    user.setId(jsonObject.getInt("userId"));
                    user.setLoginUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
                    user.setName(jsonObject.getString("userName"));
                    if (jsonObject.has("nickName")) {
                        user.setNickName(jsonObject.getString("nickName"));
                    } else {
                        user.setNickName(jsonObject.getString("userName"));
                    }

                    if (jsonObject.has("sex")) {
                        user.setSex(jsonObject.getString("sex"));
                    } else {
                        user.setSex("M");
                    }
                    if (jsonObject.has("phone")) {
                        user.setPhone(jsonObject.getString("phone"));
                    } else {
                        user.setPhone("");
                    }
                    if (jsonObject.has("mobilePhone")) {
                        user.setMobilePhone(jsonObject.getString("mobilePhone"));
                    } else {
                        user.setMobilePhone("");
                    }
                    if (jsonObject.has("email")) {
                        user.setEmail(jsonObject.getString("email"));
                    } else {
                        user.setEmail("");
                    }
                    if (jsonObject.has("userType")) {
                        user.setType(Integer.valueOf(jsonObject.getString("userType")));
                    } else {
                        user.setType(User.PERSONALFRIEND);
                    }
                    if (jsonObject.has("avatar")) {
                        if (!jsonObject.getString("avatar").equals("")
                                && jsonObject.getString("avatar").contains("http")) {
                            user.setAvatar(jsonObject.getString("avatar"));
                        } else {
                            user.setAvatar("");
                        }
                    } else {
                        user.setAvatar("");
                    }
                    if (jsonObject.has("note")) {//备注名
                        user.setReMark(jsonObject.getString("note"));
                    } else {
                        user.setReMark(user.getNickName());
                    }
                    if (jsonObject.has("sign")) {//个性签名
                        user.setSigNature(jsonObject.getString("sign"));
                    } else {
                        user.setSigNature("");
                    }

                    addFriendCallBack.addFriendCallBack(user);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onRequestFail(int requestCode, String message) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
    }

    /**
     * 添加好友时 获取好友信息
     */
    public interface AddFriendCallBack {
         void addFriendCallBack(User user);
    }
}
